#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Project    : AutomatedTesting
# @Name       : api_client.py
# @IDE        : PyCharm
# @Author     : OneYoung
# @Created    : 2025/9/5 20:41
# @Desc       : 自定义Session类，自动记录请求和响应信息

import requests
import json
from utils.log_record import logger
from application.settings import BASE_API


class SessionLogging(requests.Session):
    """自定义Session类，自动记录请求和响应信息"""

    def request(self, method, url, **kwargs) -> requests.Response:
        # 记录请求信息
        api_url = BASE_API + url
        request_info = self._format_request_log(method, api_url, **kwargs)
        logger.info(f"请求信息:\n{request_info}")

        # 发送请求
        response = super().request(method, api_url, **kwargs)

        # 记录响应信息
        response_info = self._format_response_log(response)
        logger.info(f"响应信息:\n{response_info}")

        return response

    def _format_request_log(self, method: str, url: str, **kwargs) -> str:
        """格式化请求日志"""
        log_lines = [
            f"URL: {method} {url}",
            f"Request Headers: {json.dumps(dict(self.headers), indent=2, ensure_ascii=False)}"
        ]

        # 添加请求参数
        if kwargs.get('params'):
            log_lines.append(f"Params: {json.dumps(kwargs['params'], indent=2, ensure_ascii=False)}")
        if kwargs.get('json'):
            log_lines.append(f"JSON Body: {json.dumps(kwargs['json'], indent=2, ensure_ascii=False)}")
        if kwargs.get('data'):
            log_lines.append(f"Form Data: {json.dumps(kwargs['data'], indent=2, ensure_ascii=False)}")

        return "\n".join(log_lines)

    def _format_response_log(self, response: requests.Response) -> str:
        """格式化响应日志"""
        try:
            response_json = response.json()
            formatted_body = json.dumps(response_json, indent=2, ensure_ascii=False)
        except ValueError:
            formatted_body = response.text[:500] + "..." if len(response.text) > 500 else response.text

        log_lines = [
            f"Status Code: {response.status_code}",
            f"Response Headers: {json.dumps(dict(response.headers), indent=2, ensure_ascii=False)}",
            f"Response Body: {formatted_body}"
        ]

        return "\n".join(log_lines)
